<?php
// +----------------------------------------------------------------------
// | ZGUAN [ 致力于帮助更多的中小企业物联网转型 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.zguan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ZGUAN 并不是自由软件，未经许可不能去掉ZGUAN 相关版权
// +----------------------------------------------------------------------
// | Author: ZGUAN Team <admin@zguan.cn>  0769-82282996  15899929162
// +----------------------------------------------------------------------
namespace app\controller\property\system\sms;

use api\sms\exception\SmsException;
use app\common\services\SmsService;
use think\App;
use app\controller\property\Base;
use app\validate\system\sms\SystemSmsTemplateValidate;
use app\common\repositories\system\sms\SystemSmsTemplateRepository;


class SmsTemplate extends Base
{
    protected $repository;

    public function __construct(App $app, SystemSmsTemplateRepository $repository)
    {
        parent::__construct($app);

        $this->repository = $repository;
    }

    /**
     * 短信模板列表
     * @return string|\think\response\Json
     * @throws \Exception
     *
     * @author Amos
     * 2024-01-22 17:14
     */
    public function list()
    {
        if ($this->request->isAjax()) {
            $param = $this->request->param([
                'keywords' => ''
            ]);
            [$page, $limit] = $this->getPage();
            $data = $this->repository->getpropertyList($param, $page, $limit, $this->request->propertyId);
            return json()->data(['code' => 0, 'data' => $data['list'], 'count' => $data['count']]);
        }
        return $this->fetch('system/sms/template/list', [
            'addAuth' => property_auth('propertySmsTemplateAdd'),
            'editAuth' => property_auth('propertySmsTemplateEdit'),
            'delAuth' => property_auth('propertySmsTemplateDel'),
            'testSendAuth' => property_auth('propertySmsTemplateSend'),
        ]);
    }


    /**
     * 添加短信模板
     * @return string|\think\response\Json|\think\response\View
     * @throws \Exception
     *
     * @author Amos
     * 2024-01-22 17:14
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param([
                'is_show' => '',
                'sms_type' => '',
                'template_id' => '',
                'content' => '',
                'remark' => '',
            ]);
            validate(SystemSmsTemplateValidate::class)->scene('add')->check($param);
            if ($this->repository->propertyFieldExists($this->request->propertyId, 'sms_type', $param['sms_type'])) {
                return $this->error('此模板已存在');
            }
            try {
                $res = $this->repository->addInfo($param, $this->request->propertyId, $this->request->userId);
                if ($res) {
                    return $this->success('添加成功');
                } else {
                    return $this->error('添加失败');
                }
            } catch (\Exception $e) {
                exception_log('添加菜单失败', $e);
                return $this->error('网络失败');
            }
        } else {
            $typeIds = $this->repository->getSearch([])
                ->where('property_id', $this->request->propertyId)
                ->column('sms_type');
            $templateTypes = $this->repository->templateType();
            foreach ($templateTypes as $k => $v) {
                if (in_array($k, $typeIds)) {
                    unset($templateTypes[$k]);
                }
            }
            return $this->fetch('system/sms/template/add', [
                'templateTypes' => $templateTypes
            ]);
        }
    }

    /**
     * 编辑短信模板
     * @return string|\think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *
     * @author Amos
     * 2024-01-22 17:14
     */
    public function edit()
    {
        $id = (int)$this->request->param('id');
        if (!$id) {
            return $this->error('参数错误');
        }
        $info = $this->repository->get($id);
        if (!$info) {
            return $this->error('信息获取失败');
        }
        if ($this->request->isPost()) {
            $param = $this->request->param([
                'is_show' => '',
                'sms_type' => '',
                'template_id' => '',
                'content' => '',
                'remark' => '',
            ]);
            validate(SystemSmsTemplateValidate::class)->scene('edit')->check($param);
            if ($this->repository->propertyFieldExists($this->request->propertyId, 'sms_type', $param['sms_type'], $info['id'])) {
                return $this->error('此模板已存在');
            }
            try {
                $res = $this->repository->editInfo($info, $param, $this->request->userId);
                if ($res) {
                    return $this->success('修改成功');
                } else {
                    return $this->success('没有信息发生改变');
                }
            } catch (\Exception $e) {
                exception_log('编辑菜单失败', $e);
                return $this->success('修改失败');
            }
        } else {
            return $this->fetch('system/sms/template/edit', [
                'info' => $info,
                'templateTypes' => $this->repository->templateType()
            ]);
        }
    }

    /**
     * 删除短信模板
     * @return string|\think\response\Json|\think\response\View
     *
     * @author Amos
     * 2024-01-22 17:13
     */
    public function del()
    {
        $ids = (array)$this->request->param('ids');
        try {
            $data = $this->repository->batchDelete($ids, $this->request->userId);
            if ($data) {
                return $this->success('删除成功');
            } else {
                return $this->error('删除失败');
            }
        } catch (\Exception $e) {
            exception_log('删除短信模板失败', $e);
            return $this->error('网络失败');
        }
    }

    /**
     * 发送测试短信
     * @return string|\think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *
     * @author Amos
     * 2024-01-22 17:13
     */
    public function testSend()
    {
        $id = (int)$this->request->param('id');
        if (!$this->repository->propertyExists($this->request->propertyId, $id)) {
            return $this->error('数据不存在');
        }
        $info = $this->repository->get($id);
        $phone = $this->request->param('phone');
        try {
            SmsService::init($this->request->propertyId)->sendTestContent($phone, $info['sms_type']);
            return $this->success('发送成功');
        } catch (SmsException $e) {
            return $this->error($e->getMessage());
        }
    }

}